import 'dart:async';

import 'package:flutter/material.dart';
import '../../package/color/color_constant.dart';
import '../../package/dialog/YesNoDialog.dart';
import '../../package/nav/AppBarCustom.dart';
import '../../package/package_model_comm.dart';
import 'package:yin_drag_sacle/yin_drag_sacle.dart';





/*
 * 2020.1.16
 * DingHL
 * 图片放大并且可滑动页面(局部刷新)
 */

///todo:图片显示滑动页面
class Pageview extends StatefulWidget {

  List<PhotoModel>  urlImgInfo;//图片集合
  int i;//i为第几张图片，索引从0开始
  String baseUrl;
  //删除按钮切换开关，
  bool isShowPaddingMagin;  //true 显示外面，false显示外面  默认值为true
  //图片封装加个开关  区分权限的问题，
  bool isOnTap; // true 可点击拍照按钮  false不可点击拍照按钮  默认值为true

  Pageview(
      this.urlImgInfo,
      this.i,
      this.baseUrl,
      this.isShowPaddingMagin,
      this.isOnTap,
   );



  @override
  _PageviewState createState() => _PageviewState();
}


class _PageviewState extends State<Pageview> {

  //步骤1:初始化一个StreamController<任何数据> 简单的可以扔一个int,string,开发中经常扔一个网络请求的model进去，具体看你使用场景了。
  StreamController<int> _streamController = StreamController<int>();
  StreamController<List<PhotoModel>> _streamController1 = StreamController<List<PhotoModel>>();

  int pageindex = 0;

  //接收图片的数组
  List<Widget> images = <Widget>[];

  //初始化部件
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setImages();//图片赋值方法
    //给初始化图片索引赋值
    pageindex = widget.i;
    print("pageindex初始化的值："+pageindex.toString());
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    //步骤2.关流，不管流会消耗资源，同时会引起内存泄漏
    _streamController.close();
    _streamController1.close();
  }

  //初始化图片赋值部分
  void setImages(){
    images.clear();//清除原有数据，重新赋值
    //给图片集合赋值
    for(int i = 0;i < widget.urlImgInfo.length; i++){
      images.add(
        Material(
          child: Container(
            child: Center(
              child: DragScaleContainer(
                
                child: widget.urlImgInfo[i].file!=null?
              Image.file(widget.urlImgInfo[i].file,fit: BoxFit.cover,):
              FadeInImage.assetNetwork(placeholder: "images/package/lietu1.png",image: widget.baseUrl+widget.urlImgInfo[i].url,fit: BoxFit.cover,),
                                  doubleTapStillScale: true,
                    maxScale: 4, //放大最大倍数
              ),
              
//            child: Image.network(widget.url,fit: BoxFit.cover,),
            ),
          ),
        ),
      );
    }
    _streamController1.sink.add(widget.urlImgInfo);
  }


  bool _isDisplaySubmitButton = false;
  //设置返回按钮监听事件
  Future<bool> _onWillPop() {
    setState(() {
      _isDisplaySubmitButton = true; //监听返回按钮监听事件
    });
    Navigator.of(context).pop(widget.urlImgInfo);
//    Navigator.push(context, new MaterialPageRoute(builder: (context) => null));//跳转页面
  }

  @override
  Widget build(BuildContext context) {

    // TODO: implement build
    return WillPopScope(
        onWillPop:  _onWillPop,
        child: StreamBuilder<int>(
          stream: _streamController.stream,
          initialData: pageindex,
          builder: (BuildContext context,AsyncSnapshot snapshot){
            return Scaffold(
              backgroundColor: Colors.white,
              appBar: AppBarCustom(
                left: [
                  InkWell(
                    child: Row(
                      children: <Widget>[
                        Icon(
                          Icons.arrow_back_ios,
                          color: Colors.white,
                          size: 20,
                        ),
                      ],
                    ),
//              onTap: () => Navigator.of(context).pop(),
                    onTap: (){
                      Navigator.of(context).pop();
                    },
                  ),
                ],
                right: <Widget>[
                 widget.isShowPaddingMagin == false?
                 InkWell(
                   onTap: () {
                     //删除按钮的点击
                     if(!widget.isOnTap){
                       return;
                     }
                     //取消确定弹出框
                     showDialog<Null>(
                         context: context, //BuildContext对象
                         barrierDismissible: true,//表示是否点击空白区域关闭对话框,默认为true，可以关闭
                         builder: (BuildContext context){
                           //删除提示弹出框
                           return  YesNoDialog(
                             height: 150,
                             margin: EdgeInsets.fromLTRB(40, 0, 40, 0),
//                              lineColor:Colors.grey[100],
                             ok: "确定",
                             quit: "取消",
                             circular: 10,
                             //标题
                             title: "确定要删除这张照片吗？",
                             titleFontSize: 16.0,
                             //左边点击，取消
                             onTapL: (){
                               Navigator.pop(context);
                             },
                             //右边点击，确定
                             onTapR: (){
                               for(int i = 0;i<widget.urlImgInfo.length;i++){
                                 if(widget.urlImgInfo[i].id == widget.urlImgInfo[snapshot.data].id){

                                   widget.urlImgInfo.remove(widget.urlImgInfo[i]);
                                   _streamController1.sink.add(widget.urlImgInfo);
                                   _streamController.sink.add(snapshot.data);
                                 }
                               }
                               setImages();//图片赋值

                               Navigator.pop(context);
//                                  Navigator.of(context).pop();
                               if(widget.urlImgInfo.length == 0){
                                 Navigator.pop(context);
//                                    Navigator.of(context).pop(widget.urlImgInfo);
                               }


                             },
//                            //点击回调,点击灰色区域取消操作
//                             onTapPop: (){
//                               Navigator.pop(context);
//                              },
                           );
                         }
                     );
                   },
                   child: Container(
                     child: ImageIcon(
                       AssetImage("images/package/del.png"),
                       color: Colors.white,
                     ),
                   ),
                 ):Container(),
                ],
//                title: "${pageindex+1}"+"/"+widget.urlImgInfo.length.toString(),
                title: "${snapshot.data+1}/${widget.urlImgInfo.length}",
                statusBarColor: themeColor,
              ),
              body: StreamBuilder<List<PhotoModel>>(
                  stream: _streamController1.stream,
                  initialData: widget.urlImgInfo,
                  builder: (BuildContext context,AsyncSnapshot snapshot){
                return PageView.builder(
                  // pageSnapping: false,
                  // reverse: true,
//        scrollDirection: Axis.vertical,
                  onPageChanged: (currentPage) {
                    _streamController.sink.add(currentPage);
                  },
                  controller: PageController(
                    initialPage: pageindex,
                    keepPage: false,
                    viewportFraction: 1.0,
                  ),
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context,index){
                    return images[index];
                  },
                );
              }),
            );
          },
        ),

    );
  }
}

